﻿using System.Windows;

using System.Net;
using System.Net.Sockets;


namespace TestApprovalSystem
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private double aspectRatio = 1.33; // Соотношение сторон окна

        public MainWindow()
        {
            InitializeComponent();
        }

        protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
        {
            if (sizeInfo.WidthChanged)
            {
                this.Width = sizeInfo.NewSize.Height * aspectRatio;
            }
            else
            {
                this.Height = sizeInfo.NewSize.Width / aspectRatio;
            }
        }

        private void cmdSearchAiks_Click(object sender, RoutedEventArgs e)
        {
            SearchAiks();
        }

        private void cmdStartButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void SearchAiks()
        {
            Socket mysocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 30303);

            mysocket.Bind(ipep);

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

            EndPoint Remote = (EndPoint)(sender);

            byte[] data = { 0x44, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72 };

            mysocket.SendTo(data, data.Length, SocketFlags.None, _getHost("172.16.31.6:30303"));
        }

        private EndPoint _getHost(string text)
        {
            //вырезаем из строки только IP адрес формата IPv4

            string host = text.Remove(text.IndexOf(":"), text.Length - text.IndexOf(":"));

            //создаем объект адреса. Переменная host уже имеет вид [0-255].[0-255].[0-255].[0-255]

            IPAddress hostIPAddress = IPAddress.Parse(host);

            //создаем конечную точку. В нашем случае это адрес сервера, который слушает порт 9050

            IPEndPoint hostIPEndPoint = new IPEndPoint(hostIPAddress, 30303);

            EndPoint To = (EndPoint)(hostIPEndPoint);

            return To;
        }

        #region DllFunctions

        /*//Initialize whick Aik will work with dll
        [DllImport(@"d:\Dmk\AIKproject\Binaries\dstack.dll", EntryPoint = "init_dll")]
        private static extern byte InitializeDll(byte[] ipAddress, ref byte buff, byte flag);

        // Close current Aik-dll connection
        [DllImport(@"d:\Dmk\AIKproject\Binaries\dstack.dll", EntryPoint = "close_dll")]
        private static extern byte CloseDll(byte flag);

        // Search Online Aiks
        [DllImport(@"d:\Dmk\AIKproject\Binaries\dstack.dll", EntryPoint = "discovery")]
        private static extern byte SearchAiks([Out] AikInfo[] infoA, byte[] IPshir, byte klen, ref byte dlen, byte flag);*/

        #endregion
    }
}